<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-6 lg:p-8">
    <div class="max-w-4xl mx-auto">
      <a-card title="进制转换器" class="mb-4">
        <div class="space-y-6">
          <!-- 输入区域 -->
          <div class="space-y-4">
            <div class="flex items-center space-x-4">
              <a-select
                v-model:value="inputBase"
                style="width: 120px"
                @change="convert"
              >
                <a-select-option value="2">二进制</a-select-option>
                <a-select-option value="8">八进制</a-select-option>
                <a-select-option value="10">十进制</a-select-option>
                <a-select-option value="16">十六进制</a-select-option>
              </a-select>
              <a-input
                v-model:value="inputValue"
                placeholder="输入数值"
                style="width: 300px"
                @change="convert"
                :status="inputError ? 'error' : ''"
              />
            </div>
            <div v-if="inputError" class="text-red-500 text-sm">
              {{ inputError }}
            </div>
          </div>

          <!-- 转换结果 -->
          <div class="space-y-4">
            <div v-for="base in availableBases" :key="base">
              <template v-if="Number(base) !== Number(inputBase)">
                <div class="flex items-center justify-between">
                  <span class="text-gray-600">{{ getBaseName(base) }}：</span>
                  <div class="flex items-center space-x-2">
                    <a-input
                      :value="results[base]"
                      readonly
                      style="width: 300px"
                    />
                    <a-button
                      type="text"
                      @click="copyToClipboard(results[base])"
                    >
                      <template #icon><copy-outlined /></template>
                    </a-button>
                  </div>
                </div>
              </template>
            </div>
          </div>

          <!-- 快捷操作 -->
          <div>
            <h4 class="text-sm font-medium text-gray-700 mb-2">快捷操作</h4>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
              <a-button size="small" @click="setExample('1111')">
                二进制示例
              </a-button>
              <a-button size="small" @click="setExample('377')">
                八进制示例
              </a-button>
              <a-button size="small" @click="setExample('255')">
                十进制示例
              </a-button>
              <a-button size="small" @click="setExample('FF')">
                十六进制示例
              </a-button>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 使用说明 -->
      <a-card title="使用说明" class="mb-4">
        <ol class="list-decimal list-inside space-y-2 text-gray-600">
          <li>选择输入数值的进制（2/8/10/16进制）</li>
          <li>输入需要转换的数值</li>
          <li>自动显示其他进制的转换结果</li>
          <li>点击复制按钮可复制转换结果</li>
          <li>支持正整数的进制转换</li>
        </ol>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { CopyOutlined } from '@ant-design/icons-vue'

// 可用进制
const availableBases = [2, 8, 10, 16]

// 输入状态
const inputBase = ref('10')
const inputValue = ref('')
const inputError = ref('')

// 转换结果
const results = ref<Record<number, string>>({
  2: '',
  8: '',
  10: '',
  16: ''
})

// 进制名称映射
const getBaseName = (base: number) => {
  const names: Record<number, string> = {
    2: '二进制',
    8: '八进制',
    10: '十进制',
    16: '十六进制'
  }
  return names[base]
}

// 验证输入
const validateInput = (value: string, base: number) => {
  if (!value) return false

  const patterns: Record<number, RegExp> = {
    2: /^[01]+$/,
    8: /^[0-7]+$/,
    10: /^\d+$/,
    16: /^[0-9A-Fa-f]+$/
  }

  const pattern = patterns[base]
  if (!pattern || !pattern.test(value)) {
    inputError.value = `请输入有效的${getBaseName(base)}数值`
    return false
  }

  // 检查是否超出范围
  try {
    const decimal = parseInt(value, base)
    if (decimal > Number.MAX_SAFE_INTEGER) {
      inputError.value = '数值超出范围'
      return false
    }
  } catch {
    inputError.value = '数值无效'
    return false
  }

  inputError.value = ''
  return true
}

// 转换函数
const convert = () => {
  if (!inputValue.value) {
    results.value = { 2: '', 8: '', 10: '', 16: '' }
    return
  }

  const base = parseInt(inputBase.value)
  if (!validateInput(inputValue.value, base)) return

  try {
    // 先转为十进制
    const decimal = parseInt(inputValue.value, base)

    // 转换为其他进制
    results.value = {
      2: decimal.toString(2),
      8: decimal.toString(8),
      10: decimal.toString(10),
      16: decimal.toString(16).toUpperCase()
    }
  } catch (error) {
    message.error('转换失败')
  }
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    message.success('已复制到剪贴板')
  } catch {
    message.error('复制失败')
  }
}

// 设置示例
const setExample = (value: string) => {
  switch (value) {
    case '1111':
      inputBase.value = '2'
      break
    case '377':
      inputBase.value = '8'
      break
    case '255':
      inputBase.value = '10'
      break
    case 'FF':
      inputBase.value = '16'
      break
  }
  inputValue.value = value
  convert()
}
</script> 